package com.lin.manager.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.manager.common.resp.DataPage;
import com.lin.manager.common.utils.IPUtils;
import com.lin.manager.secure.model.SecurityLog;
import com.lin.manager.system.dao.SysLoginLogDao;
import com.lin.manager.system.entity.SysLoginLogEntity;
import com.lin.manager.system.model.vo.LogQueryParamVO;
import com.lin.manager.system.service.SysLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @作者: 林江
 * @创建时间: 2024-03-19 14:51:14
 * @功能:
 */
@Slf4j
@Service("loginLogService")
public class SysLoginLogServiceImpl implements SysLoginLogService {
    @Resource
    private SysLoginLogDao sysLoginLogDao;

    @Override
    public void addLog(SecurityLog securityLog) {
        SysLoginLogEntity loginLog = new SysLoginLogEntity();
        loginLog.setId(securityLog.getId());
        loginLog.setCreateTime(securityLog.getCreateTime());
        loginLog.setDescript(securityLog.getDescript());
        loginLog.setStatus(securityLog.getStatus());
        loginLog.setUserName(securityLog.getUserName());
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        loginLog.setIp(IPUtils.getIpAddr(request));
        loginLog.setMethod(request.getMethod());

        sysLoginLogDao.insert(loginLog);
    }

    @Override
    public void delLog(Object id) {
        sysLoginLogDao.deleteById(id.toString());
    }

    @Override
    public DataPage listLogLoginByPage(LogQueryParamVO pageVO) {
        LambdaQueryWrapper<SysLoginLogEntity> wrapper = new QueryWrapper<SysLoginLogEntity>().lambda()
                .orderByDesc(SysLoginLogEntity::getCreateTime)
                .ge(StringUtils.hasText(pageVO.getStartTime()), SysLoginLogEntity::getCreateTime, pageVO.getStartTime())
                .le(StringUtils.hasText(pageVO.getEndTime()), SysLoginLogEntity::getCreateTime, pageVO.getEndTime());

        Page<SysLoginLogEntity> selectPage = sysLoginLogDao.selectPage(new Page<>(pageVO.getPageNum(), pageVO.getPageSize()), wrapper);
        return DataPage.<SysLoginLogEntity>builder().page(selectPage).build();
    }


}
